package com.xjx.common.util;

/**
 * created by xjx on  2023-10-30 16:38
 */

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class HttpsUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpsUtils.class);
    static CloseableHttpClient httpClient;
    static CloseableHttpResponse httpResponse;

    public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();

    }


    public static InputStream sendGet(String url) {
        String result = null;
        try {
            httpClient = new SSLClient();
            HttpGet httpGet = new HttpGet(url);

            try {
                CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpGet);

                if (null != closeableHttpResponse && !"".equals(closeableHttpResponse)) {
                    if (closeableHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        HttpEntity httpEntity = closeableHttpResponse.getEntity();
                        if (Objects.nonNull(httpEntity)) {
                            InputStream inputStream = httpEntity.getContent();
                            return inputStream;
                        }
                    } else {
                        HttpEntity httpEntity = closeableHttpResponse.getEntity();
                        result = EntityUtils.toString(httpEntity, "UTF-8");
                        logger.error("error url:" + httpGet.toString());
                    }
                }
            } catch (ClientProtocolException e) {
                logger.error("协议异常", e);
                return null;
            } catch (ParseException e) {
                logger.error("解析异常", e);
                return null;
            } catch (IOException e) {
                logger.error("传输异常", e);
                return null;
            } finally {
                try {
                    if (httpClient != null) {
                        httpClient.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }


    public static String sendGetRequest(String requestUrl) {
        String result = null;
        try {
            httpClient = new SSLClient();
            HttpGet httpGet = new HttpGet(requestUrl);

            try {
                CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpGet);

                if (null != closeableHttpResponse && !"".equals(closeableHttpResponse)) {
                    if (closeableHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        HttpEntity httpEntity = closeableHttpResponse.getEntity();
                        result = EntityUtils.toString(httpEntity, "UTF-8");
                    } else {
                        HttpEntity httpEntity = closeableHttpResponse.getEntity();
                        result = EntityUtils.toString(httpEntity, "UTF-8");
                        logger.error("error url:" + httpGet.toString());
                    }
                }
                return result;
            } catch (ClientProtocolException e) {
                logger.error("协议异常", e);
                return null;
            } catch (ParseException e) {
                logger.error("解析异常", e);
                return null;
            } catch (IOException e) {
                logger.error("传输异常", e);
                return null;
            } finally {
                try {
                    if (httpClient != null) {
                        httpClient.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }


    private static String get(HttpGet httpGet, CloseableHttpClient closeableHttpClient) {
        if (closeableHttpClient == null) {
            closeableHttpClient = createSSLClientDefault();
        }
        try {
            CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpGet);
            String result = null;
            if (null != closeableHttpResponse && !"".equals(closeableHttpResponse)) {
                if (closeableHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity httpEntity = closeableHttpResponse.getEntity();
                    result = EntityUtils.toString(httpEntity, "UTF-8");
                } else {
                    HttpEntity httpEntity = closeableHttpResponse.getEntity();
                    result = EntityUtils.toString(httpEntity, "UTF-8");
                    logger.error("error url:" + httpGet.toString());
                }
            }
            return result;
        } catch (ClientProtocolException e) {
            logger.error("协议异常", e);
            return null;
        } catch (ParseException e) {
            logger.error("解析异常", e);
            return null;
        } catch (IOException e) {
            logger.error("传输异常", e);
            return null;
        } finally {
            try {
                if (closeableHttpClient != null) {
                    closeableHttpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    /**
     * 发送https请求
     *
     * @param params
     * @throws Exception
     */
    public static String sendByHttp(Map<String, Object> params, String url) {
        try {
            HttpPost httpPost = new HttpPost(url);
            List<NameValuePair> listNVP = new ArrayList<NameValuePair>();
            if (params != null) {
                for (String key : params.keySet()) {
                    listNVP.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(listNVP, "UTF-8");
            logger.info("创建请求httpPost-URL={},params={}", url, listNVP);
            httpPost.setEntity(entity);
            httpClient = HttpsUtils.createSSLClientDefault();
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                String jsObject = EntityUtils.toString(httpEntity, "UTF-8");
                return jsObject;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                httpResponse.close();
                httpClient.close();
                logger.info("请求流关闭完成");
            } catch (IOException e) {
                logger.info("请求流关闭出错");
                e.printStackTrace();
            }
        }
    }

}
